package org.origin.ferret.center.configs;


import org.origin.centre.aspect.AspectInterceptor;
import org.origin.centre.config.AutoRedisConfig;
import org.origin.centre.filter.HandlerFilterException;
import org.origin.centre.filter.XssHeaderEnhanceFilter;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 配置自定义 WebMvcConfigurer 配置
 *
 * @author ferret
 * @version 2024-05-08
 */
@Configuration
@Import({XssHeaderEnhanceFilter.class, AspectInterceptor.class})
@ImportAutoConfiguration(AutoRedisConfig.class)
public class MyViewConfig implements WebMvcConfigurer {

    /**
     * 配置全局异常处理
     */
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new HandlerFilterException(true));
    }

    /**
     * 配置静态资源访问路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置通用访问路径；设置虚拟路径，访问绝对路径下资源
        registry.addResourceHandler("/origin/file").addResourceLocations("file:C:/origin/file/**");
        // 配置knife4j访问路径
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/doc.html");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 配置跨域访问
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

}
